<?php

namespace App\Http\Controllers\Account;

use App\Models\UserModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Components\UserComponent;

use DB;
use App\Models\UserAccountModel;
use App\Models\AccountBillModel;

/*
* 可提现金额
*/
class BalanceController extends AccountController{

    public function __construct(){
         parent::__construct();
    }
    
    /*版本控制，对应app版本跳转对应接口*/
    public function version_invoke(Request $request){
        $appversion = $request->input('appversion');
        $apptype = $request->input('apptype');
        if ($appversion && $apptype) {
            return $this->balance($request);
        }else{
            return $this->json('102','该app版本下无此接口，请更新app');
        }
    }

    /*
    * 获取当前用户收入支出
    * @param $user_id   用户id
    * @return 
    */
    public function balance(Request $request){
        // 检验当前登录是否有效
        $user = UserComponent::check_token($request);
        $user_id = $user['user_id'];

        $account = UserAccountModel::where(['user_id'=>$user_id])->first();
        if ($account) {
            $bill_amount = AccountBillModel::where(['user_id'=>$user_id,'status'=>'succeeded'])->sum('amount');
            if ($bill_amount == $account->balance) {
                $data['balance'] = number_format(floatval($account->balance  / 100),2);
            }else{
                $newaccount = UserAccountModel::where(['user_id'=>$user_id])->first();
                $newaccount->balance = $bill_amount;
                $newaccount->saveOrFail();
                $data['balance'] = number_format(floatval($bill_amount  / 100),2);
            }

            $data['has_pay_password'] = ($account->pay_password)?'1':'0';
            $user =  UserModel::firstOrNew(['user_id'=>$user_id]);
            $data['has_phone'] = $user->phone? '1':'0';
            return $this->json('1','',$data); 
        }else{
            return $this->json('0','未获取到账号信息'); 
        }
    }
}
